package cn.vivi.recyclercomp.custom;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ProgressBar;
import android.widget.TextView;
import cn.vivi.recyclercomp.Status;
import cn.vivi.recyclercomp.fragment.RecyclerGridViewFragment;

@SuppressLint("ValidFragment")
public class CustomGridViewFragment extends RecyclerGridViewFragment {

	private static final String KEY_SPAN_COUNT = "key_span_count";
	private String mSpanCount;


	public CustomGridViewFragment(int spanCount) {
		super(spanCount);
	}


	public static CustomGridViewFragment newInstance(int spanCount) {
		CustomGridViewFragment frag = new CustomGridViewFragment(spanCount);
		Bundle args = new Bundle();
		args.putInt(KEY_SPAN_COUNT, spanCount);
		frag.setArguments(args);
		return frag;
	}


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle args = getArguments();
		if (args != null) {
			mSpanCount = args.getString(KEY_SPAN_COUNT);
		}

	}


	@Override
	public void initialize() {
		super.initialize();
		// 不设置divider
		// clearDecorations();

		// setLoadingLayoutEnabled(false);
		// setRefreshLayoutEnabled(false);
		setLoadingLayout(createLoadingLayout());
		startLoading();

	}


	private LoadingLayout createLoadingLayout() {
		TextView idle = new TextView(getActivity());
		idle.setText("waiting...");
		TextView finish = new TextView(getActivity());
		finish.setText("all downloaded");
		finish.setBackgroundColor(Color.parseColor("#ff0000"));
		finish.setGravity(Gravity.CENTER);
		ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		finish.setLayoutParams(params);
		TextView error = new TextView(getActivity());
		error.setText("error");
		TextView unreachNet = new TextView(getActivity());
		unreachNet.setText("unreach Network");
		ProgressBar loading = new ProgressBar(getActivity());
		loading.setIndeterminate(true);

		LoadingLayout layout = new LoadingLayout(getActivity(), idle, loading, error, finish, unreachNet);
		return layout;
	}


	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
	}


	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		return false;
	}


	@Override
	public CustomRecyclerAdapter createAdapter() {
		CustomRecyclerAdapter adapter = new CustomRecyclerAdapter(getActivity(), null);
		return adapter;
	}

	private final static String TEST_URL = "http://apitest.baoruan.com/launcher/default/index?version=9.150320&un=239BA6301606E596F70AC1E7B4808B23&name=recommendlist&channelId=ceshi_baoruanservice1";

	private int counter = 0;


	@Override
	public void onStartLoading() {
		final FinalHttp fh = new FinalHttp();
		AjaxParams params = new AjaxParams();
		fh.get(TEST_URL, params, new AjaxCallBack<String>() {

			@Override
			public void onSuccess(String t) {
				try {
					JSONObject json = new JSONObject(t);
					JSONArray arrayJson = json.getJSONArray("list");
					if (arrayJson != null) {
						for (int i = 0; i < arrayJson.length(); i++) {
							JSONObject dataJson = arrayJson.getJSONObject(i);
							String name = dataJson.optString("name");
							getAdapter().getData().add(name);
							getAdapter().notifyItemInserted(getAdapter().getData().size());
						}
						setStatus(Status.CONTENT);
						hideRefreshView();
					}
					counter++;
					if (counter == 2) {
						onStateChanged(LoadState.ERROR);

					} else if (counter == 4) {
						onStateChanged(LoadState.END);
					} else {
						onStateChanged(LoadState.FINISH);
					}

					/* "id": "301", 
					    "download_id": "60092871", 
					    "description": "乐玩游戏", 
					    "name": "乐玩游戏", 
					    "type": "4", 
					    "order": "0", 
					    "status": "1", 
					    "class_id": "2", 
					    "packageName": "com.baoruan.lewan", 
					    "file_size": "3954", 
					    "icoUrl": "http://x1.17xgame.com//d/soft/2015/02/12/46235df4f8682ba23037.png", 
					    "downUrl": "http://apitest.baoruan.com/launcher/default/appdownbyid/id/60092871?channelId=ceshi_baoruanservice1&version=9.150320&imei=239BA6301606E596F70AC1E7B4808B23"
					*/
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}


			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				t.printStackTrace();

			}


			@Override
			public void onStart() {
			}
		});

	}

}
